from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

from django.views import View

from register.forms import RegisterForm
from users.models import UserProfile


class RegisterView(View):
    """
    注册类视图
    """

    def get(self, request):
        """
        返回注册页面
        :param request:
        :return: register.html
        """
        # 实例化表单对象
        register_form = RegisterForm()
        # 返回响应
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        """
        注册实现
        :param request:
        :return:
        """
        # 接收表单数据
        data = request.POST
        # 生成表单对象
        register_form = RegisterForm(data=data)
        # 对传入的数据进行验证 当验证失败返回空值
        result = register_form.is_valid()
        # 储存错误信息，以便返回
        errors = register_form.errors
        # 若result不为空则验证成功
        if result:
            email = register_form.data['email']
            try:
                user = UserProfile.objects.get(email=email)
            # 用户存在则返回错误信息
            except:
                password = register_form.data['password']
                #  保存信息
                user = UserProfile.objects.create_user(
                    email=email,
                    password=password,
                    username=email
                )
                login(request, user=user)
                return redirect('/info/')
            else:
                return render(request, 'register.html', {'msg': '邮箱已存在'})
                # return http.HttpResponseBadRequest('邮箱已存在')
        return render(request, 'register.html', {'register_form': register_form})
